/**
 * Created by Administrator on 2017/2/13.
 */

var DBFactory = require('../conn/DBFactory');
var hidCouDao = module.exports;
var cheerio = require('cheerio');
var request = require('request');
// var proxyReqInstance = require('../global_var');

hidCouDao.expired = function (activityId, sellerId, itemId, cb) {
    // var url = 'https://uland.taobao.com/cp/coupon?activityId=' + activityId + '&itemId=' + itemId + '&sellerId=' + sellerId;
    var url = 'http://uland.htaoke.com/cp/coupon?activityId=' + activityId + '&itemId=' + itemId + '&sellerId=' + sellerId;
    var options = {
        url : url,
        timeout : 5000
    };
    function callback(error, response, body) {
        if(error || response.statusCode != 200 || !body){
            // console.log(error);
            cb('获取ip失败');
            return;
        }
        try {
            if(!body || body.length < 2){
                cb('获取隐藏券失败');
                return;
            }
            if(body.substr(0, 1) != '{'){
                if(body.indexOf('访问受限')){
                    cb('访问受限');
                    return;
                }
                cb('获取隐藏券失败');
                return;
            }
            var rsp = JSON.parse(body);
            if(!rsp || !rsp.result || !rsp.success){
                cb('获取隐藏券失败');
                console.log(body);
                return false;
            } 

            if(rsp.result.amount <= 0 || rsp.result.amount == null){
                cb(null, {couponAmount:0});
                return false;
            }

            var couponInfo = {url:url, activityId:activityId, itemId:itemId};
            couponInfo.couponAmount = rsp.result.amount;
            couponInfo.startFee = rsp.result.startFee;
            couponInfo.couponEffectiveStartTime = rsp.result.effectiveStartTime;
            couponInfo.couponEffectiveEndTime = rsp.result.effectiveEndTime;
            cb(null, couponInfo);
        }
        catch (e) {
            cb(e);
            console.log(e);
        }
    }
    // proxyReqInstance.proxyRequest(options, callback);
    request(options, callback);
}
